import React, { createContext, useContext, useEffect, useRef, useState } from 'react'

type Toast = { id: number; message: string; type?: 'info' | 'success' | 'error' }

type ToastCtx = {
  show: (message: string, type?: Toast['type']) => void
}

const Ctx = createContext<ToastCtx | null>(null)

export function useToast(): ToastCtx {
  const ctx = useContext(Ctx)
  if (!ctx) throw new Error('ToastProvider missing')
  return ctx
}

export function ToastProvider({ children }: { children: React.ReactNode }): JSX.Element {
  const [toasts, setToasts] = useState<Toast[]>([])
  const idRef = useRef(1)

  const show = (message: string, type: Toast['type'] = 'info') => {
    const id = idRef.current++
    setToasts((prev) => [...prev, { id, message, type }])
    setTimeout(() => {
      setToasts((prev) => prev.filter((t) => t.id !== id))
    }, 2500)
  }

  return (
    <Ctx.Provider value={{ show }}>
      {children}
      <div className="toast-stack">
        {toasts.map((t) => (
          <div key={t.id} className={`toast toast-${t.type}`}>{t.message}</div>
        ))}
      </div>
    </Ctx.Provider>
  )
}

